package com.example.controller;

import com.example.model.LaundryOrder;
import com.example.model.User;
import com.example.service.LaundryOrderService;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户端API", description = "用户端专用的API接口")
public class UserApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private LaundryOrderService laundryOrderService;

    // ==================== 用户资料管理 ====================
    @GetMapping("/profile")
    @Operation(summary = "获取用户资料")
    public ResponseEntity<Map<String, Object>> getUserProfile() {
        // 这里应该从SecurityContext获取当前用户
        Map<String, Object> profile = new HashMap<>();
        profile.put("id", 1L);
        profile.put("username", "customer");
        profile.put("email", "customer@example.com");
        profile.put("phone", "13800138000");
        profile.put("realName", "张三");
        profile.put("avatar", "/avatars/default.jpg");
        profile.put("memberLevel", "GOLD");
        profile.put("points", 1250);
        profile.put("totalOrders", 45);
        profile.put("totalSpent", 8500.0);
        
        return ResponseEntity.ok(profile);
    }

    @PutMapping("/profile")
    @Operation(summary = "更新用户资料")
    public ResponseEntity<Map<String, Object>> updateUserProfile(@RequestBody Map<String, Object> profileData) {
        // 这里应该实现用户资料更新逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户资料更新成功");
        
        return ResponseEntity.ok(response);
    }

    @PutMapping("/password")
    @Operation(summary = "修改密码")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> passwordData) {
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        
        // 这里应该实现密码修改逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "密码修改成功");
        
        return ResponseEntity.ok(response);
    }

    @PostMapping("/avatar")
    @Operation(summary = "上传头像")
    public ResponseEntity<Map<String, Object>> uploadAvatar(@RequestParam("file") String file) {
        // 这里应该实现头像上传逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "头像上传成功");
        response.put("avatarUrl", "/avatars/user_1.jpg");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 用户设置 ====================
    @GetMapping("/settings")
    @Operation(summary = "获取用户设置")
    public ResponseEntity<Map<String, Object>> getUserSettings() {
        Map<String, Object> settings = new HashMap<>();
        settings.put("notifications", Map.of(
            "orderUpdates", true,
            "promotions", true,
            "systemMessages", false
        ));
        settings.put("privacy", Map.of(
            "showProfile", true,
            "showOrderHistory", false
        ));
        settings.put("preferences", Map.of(
            "language", "zh-CN",
            "theme", "light",
            "autoLogin", true
        ));
        
        return ResponseEntity.ok(settings);
    }

    @PutMapping("/settings")
    @Operation(summary = "更新用户设置")
    public ResponseEntity<Map<String, Object>> updateUserSettings(@RequestBody Map<String, Object> settingsData) {
        // 这里应该实现用户设置更新逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户设置更新成功");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 用户订单 ====================
    @GetMapping("/orders")
    @Operation(summary = "获取用户订单列表")
    public ResponseEntity<Page<LaundryOrder>> getUserOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String status) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 这里应该根据当前用户ID过滤订单
        Page<LaundryOrder> orders = laundryOrderService.getAllOrders(pageable);
        return ResponseEntity.ok(orders);
    }

    @GetMapping("/orders/{id}")
    @Operation(summary = "获取用户订单详情")
    public ResponseEntity<LaundryOrder> getUserOrderDetail(@PathVariable Long id) {
        return laundryOrderService.getOrderById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // ==================== 用户地址管理 ====================
    @GetMapping("/addresses")
    @Operation(summary = "获取用户地址列表")
    public ResponseEntity<List<Map<String, Object>>> getUserAddresses() {
        List<Map<String, Object>> addresses = List.of(
            Map.of(
                "id", 1L,
                "name", "张三",
                "phone", "13800138000",
                "province", "北京市",
                "city", "北京市",
                "district", "朝阳区",
                "detail", "三里屯街道123号",
                "isDefault", true
            ),
            Map.of(
                "id", 2L,
                "name", "张三",
                "phone", "13800138000",
                "province", "北京市",
                "city", "北京市",
                "district", "海淀区",
                "detail", "中关村大街456号",
                "isDefault", false
            )
        );
        
        return ResponseEntity.ok(addresses);
    }

    @PostMapping("/addresses")
    @Operation(summary = "添加用户地址")
    public ResponseEntity<Map<String, Object>> addUserAddress(@RequestBody Map<String, Object> addressData) {
        // 这里应该实现添加地址的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "地址添加成功");
        response.put("id", 3L);
        
        return ResponseEntity.ok(response);
    }

    @PutMapping("/addresses/{id}")
    @Operation(summary = "更新用户地址")
    public ResponseEntity<Map<String, Object>> updateUserAddress(
            @PathVariable Long id,
            @RequestBody Map<String, Object> addressData) {
        
        // 这里应该实现更新地址的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "地址更新成功");
        
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/addresses/{id}")
    @Operation(summary = "删除用户地址")
    public ResponseEntity<Map<String, Object>> deleteUserAddress(@PathVariable Long id) {
        // 这里应该实现删除地址的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "地址删除成功");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 用户权限和菜单 ====================
    @GetMapping("/permissions")
    @Operation(summary = "获取用户权限")
    public ResponseEntity<List<String>> getUserPermissions() {
        List<String> permissions = List.of(
            "ORDER_VIEW",
            "ORDER_CREATE",
            "PROFILE_EDIT",
            "ADDRESS_MANAGE"
        );
        
        return ResponseEntity.ok(permissions);
    }

    @GetMapping("/menus")
    @Operation(summary = "获取用户菜单")
    public ResponseEntity<List<Map<String, Object>>> getUserMenus() {
        List<Map<String, Object>> menus = List.of(
            Map.of(
                "id", 1L,
                "name", "我的订单",
                "path", "/user/orders",
                "icon", "order",
                "children", List.of()
            ),
            Map.of(
                "id", 2L,
                "name", "个人中心",
                "path", "/user/profile",
                "icon", "user",
                "children", List.of(
                    Map.of("id", 21L, "name", "基本信息", "path", "/user/profile/basic"),
                    Map.of("id", 22L, "name", "地址管理", "path", "/user/profile/address"),
                    Map.of("id", 23L, "name", "账户设置", "path", "/user/profile/settings")
                )
            )
        );
        
        return ResponseEntity.ok(menus);
    }

    // ==================== 用户收藏 ====================
    @GetMapping("/favorites")
    @Operation(summary = "获取用户收藏")
    public ResponseEntity<List<Map<String, Object>>> getUserFavorites() {
        List<Map<String, Object>> favorites = List.of(
            Map.of(
                "id", 1L,
                "type", "SERVICE",
                "itemId", 1L,
                "itemName", "精品干洗",
                "itemImage", "/images/service1.jpg",
                "createdAt", "2024-11-01 10:00:00"
            ),
            Map.of(
                "id", 2L,
                "type", "MERCHANT",
                "itemId", 1L,
                "itemName", "示例洗衣店",
                "itemImage", "/images/merchant1.jpg",
                "createdAt", "2024-11-02 15:30:00"
            )
        );
        
        return ResponseEntity.ok(favorites);
    }

    @PostMapping("/favorites")
    @Operation(summary = "添加收藏")
    public ResponseEntity<Map<String, Object>> addFavorite(@RequestBody Map<String, Object> favoriteData) {
        // 这里应该实现添加收藏的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "收藏成功");
        
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/favorites/{id}")
    @Operation(summary = "取消收藏")
    public ResponseEntity<Map<String, Object>> removeFavorite(@PathVariable Long id) {
        // 这里应该实现取消收藏的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "取消收藏成功");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 用户消息 ====================
    @GetMapping("/messages")
    @Operation(summary = "获取用户消息")
    public ResponseEntity<Page<Map<String, Object>>> getUserMessages(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 这里应该实现获取用户消息的逻辑
        // 暂时返回空的分页结果
        Pageable pageable = PageRequest.of(page, size);
        return ResponseEntity.ok(Page.empty(pageable));
    }

    @PutMapping("/messages/{id}")
    @Operation(summary = "标记消息为已读")
    public ResponseEntity<Map<String, Object>> markMessageAsRead(@PathVariable Long id) {
        // 这里应该实现标记消息为已读的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "消息已标记为已读");
        
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/messages/{id}")
    @Operation(summary = "删除消息")
    public ResponseEntity<Map<String, Object>> deleteMessage(@PathVariable Long id) {
        // 这里应该实现删除消息的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "消息删除成功");
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/messages/unread-count")
    @Operation(summary = "获取未读消息数量")
    public ResponseEntity<Map<String, Object>> getUnreadMessageCount() {
        Map<String, Object> response = new HashMap<>();
        response.put("count", 5);
        
        return ResponseEntity.ok(response);
    }
}
